<template>
	<view class="courses-container">
		<uv-toast ref="toast"></uv-toast>
		<!-- 顶部搜索栏 -->
		<view class="search-bar">
			<uv-input placeholder="搜索课程名称" prefixIcon="search" prefixIconStyle="font-size: 24px;color: #999"
				v-model="searchKey" shape="circle"
				:customStyle="{ background: '#f0f0f0', fontSize: '28rpx', color: '#333' }" @confirm="onSearch"
				confirmType="search" :disabled="loading">
				<!-- 添加搜索按钮 -->
				<template #suffix>
					<view class="search-btn" @tap="onSearch" :class="{ 'loading': loading }">
						<uv-loading-icon v-if="loading" size="26" mode="circle" color="#ffffff"></uv-loading-icon>
						<text v-else>搜索</text>
					</view>
				</template>
			</uv-input>


			<!-- 分类筛选 -->
			<view class="filter-bar">
				<view v-for="(item, index) in filterList" :key="index" class="filter-item"
					:class="{ active: currentFilter === item.type }" @click="changeFilter(item.type)">
					<text>{{ item.name }}</text>
					<text class="sort-icon" v-if="item.sort">{{ item.sort === 'asc' ? '↑' : '↓' }}</text>
				</view>
			</view>
		</view>

		<view class="empty" v-if="!orderList || orderList.length === 0">
			<uv-empty textColor="#8094b9" textSize="28" iconColor="#8094b9" iconSize="100" text="暂无已购课程"></uv-empty>
		</view>

		<!-- 课程列表 -->
		<view class="course-card" v-for="(course, idx) in orderList" :key="idx" @tap="handleContinue(course.courseMedia.id, course.id, course.status )">
			<!-- 课程封面区域 -->
			<view class="cover-section">
				<image :src="course.image" mode="aspectFill" class="cover-image" />
				<!-- 状态标识 -->
				<view class="status-badge" :class="{ 'unpublished': course.status === 0 }">
					{{ course.status === 1 ? '已上线' : '未发布' }}
				</view>
				<!-- 仅在课程已发布时显示进度 -->
				<view class="progress-overlay" v-if="course.status === 1">
					<view class="progress-bar">
						<view class="progress-inner"
							:style="{ width: `${course.videoPlayProgress.watchPercent || 0}%` }">
						</view>
					</view>
					<text class="progress-text">已学习 {{ course.videoPlayProgress.watchPercent || 0 }}%</text>
				</view>
			</view>

			<!-- 课程信息区域 -->
			<view class="content-section">
				<view class="title-row">
					<text class="course-title">{{ course.name }}</text>
					<view class="status-tag" :class="course.status === 1 ? 'status-published' : 'status-unpublished'">
						{{ getStatusText(course) }}
					</view>
				</view>

				<!-- 最近学习信息 - 仅在课程已发布时显示 -->
				<view class="latest-study" v-if="course.status === 1 && course.courseMedia">
					<view class="chapter-info">
						<text class="chapter-title">{{ course.courseMedia.title }}</text>
						<text class="continue-btn">继续学习</text>
					</view>
					<view class="study-stats">
						<text class="time-info">上次学习: {{ formatDate(course.videoPlayProgress.lastPlayTime) }}</text>
						<text class="duration">已学习{{ formatDuration(course.videoPlayProgress.totalPlayDuration)}}</text>
					</view>
				</view>

				<!-- 未发布提示 -->
				<view class="unpublished-tip" v-else-if="course.status === 0">
					<text class="tip-text">课程准备中，敬请期待</text>
					<text class="expected-date" v-if="course.onlineDate">
						预计上线时间: {{ formatDate(course.onlineDate) }}
					</text>
				</view>

				<!-- 课程标签 -->
				<view class="tags-row">
					<text v-for="(tag, index) in course.tags.split(',')" :key="index" class="tag">{{ tag }}</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import debounce from '@/uni_modules/uv-ui-tools/libs/function/debounce.js';
	export default {
		data() {
			return {
				filterList: [{
						name: '购买时间',
						type: 'buyTime',
						sort: 'desc'
					},
					{
						name: '观看记录',
						type: 'watchTime',
						sort: 'desc'
					}
				],
				orderList: [],
				page: 1,
				loading: false,
				isRefreshing: false,
				hasMore: true,
				currentFilter: 'buyTime',
				searchKey: '',
			}
		},

		onLoad() {
			this.fetchOrder()
		},

		methods: {
			formatDuration(seconds) {
				if (!seconds) return '0分钟';

				// 转换为数字确保计算准确
				seconds = Number(seconds);

				// 计算小时、分钟、秒
				const hours = Math.floor(seconds / 3600);
				const minutes = Math.floor((seconds % 3600) / 60);
				const remainingSeconds = Math.floor(seconds % 60);

				// 根据时长选择不同的显示格式
				if (hours > 0) {
					// 超过1小时，显示 "x小时y分钟"
					return `${hours}小时${minutes > 0 ? minutes + '分钟' : ''}`;
				} else if (minutes > 0) {
					// 不足1小时，显示 "x分钟"
					return `${minutes}分钟`;
				} else {
					// 不足1分钟，显示 "x秒"
					return `${remainingSeconds}秒`;
				}
			},
			getStatusText(course) {
				return course.status === 1 ? '已购买' : '未发布';
			},
			showToast(msg, type = 'default', duration = 1000) {
				this.$refs.toast.show({
					message: msg,
					type: type,
					duration: duration,
				})
			},
			handleContinue(mediaId, courseId, courseStatus) {
				if (courseStatus === 0) {
					this.showToast('课程未发布');
					return;
				}
				uni.navigateTo({
					url: `/subpkg/video_pay_course_play/video_pay_course_play?courseId=${courseId}&courseMediaId=${mediaId}`
				})
			},
			formatDate(dateStr) {
				if (!dateStr) return '';
				const date = new Date(dateStr);
				return `${date.getMonth() + 1}月${date.getDate()}日`;
			},
			async changeFilter(type) {
				if (this.currentFilter === type || this.loading) return;
				this.currentFilter = type;
				await this.fetchOrder(true);
			},
			async fetchOrder(reset = false) {
				if (this.loading || (!this.hasMore && !reset)) return

				try {
					this.loading = true
					const params = {
						pageNum: reset ? 1 : this.page,
						pageSize: 5,
						keyWord: this.searchKey,
						orderByBuyTimeDesc: this.currentFilter === 'buyTime',
						orderByWatchTimeDesc: this.currentFilter === 'watchTime'
					}

					const res = await this.$http.post('/order/search', params)

					if (reset) {
						this.orderList = res.items
						this.page = 2
					} else {
						this.orderList = [...this.orderList, ...res.items]
						this.page++
					}

					this.hasMore = res.count > this.orderList.length;
				} catch (e) {
					this.showToast('加载失败');
				} finally {
					this.loading = false
					if (this.isRefreshing) {
						this.isRefreshing = false
					}
				}
			},

			// 搜索方法
			onSearch() {
				if (this.loading) return;
				debounce(() => {
					this.fetchOrder(true);
				}, 500);
			},

			loadMore() {
				if (!this.loading && this.hasMore) {
					this.fetchOrder()
				}
			},

			async onRefresh() {
				this.isRefreshing = true
				await this.fetchOrder(true)
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import 'my_courses.scss';
</style>